package com.letu.mq.config;

import com.letu.mq.listener.BusinessPointListner;
import com.letu.mq.service.CheckTopicTagServer;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * 因为RocketMQMessageListener不提供动态配置功能
 * springboot初始化后rocket容器初始化前利用反射动态改变
 * RocketMQMessageListener注解selectorExpression的值
 * 单事件mq：动态组装tag值
 */
//@Component
public class ChangeSelectorExpressionBeforeMqStartOfBusiness implements InitializingBean {
    @Autowired
    CheckTopicTagServer checkTopicTagServer;

    @Override
    public void afterPropertiesSet() throws Exception {
        RocketMQMessageListener annoTable =
                BusinessPointListner.class.getAnnotation(RocketMQMessageListener.class);
        // 获取代理处理器
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(annoTable);
        // 获取私有 memberValues 属性
        Field f = invocationHandler.getClass().getDeclaredField("memberValues");
        f.setAccessible(true);
        // 获取实例的属性map
        Map<String, Object> memberValues = (Map<String, Object>)
                f.get(invocationHandler);
        // 修改属性值
        memberValues.put("selectorExpression", checkTopicTagServer.assembleTagOfBuiness());

    }

}
